package com.example.mahao_final.UI

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.mahao_final.MainActivity
import com.example.mahao_final.R
import com.example.mahao_final.database.UserDatabase
import com.example.mahao_final.entity.User
import com.example.mahao_final.utils.PasswordUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class LoginActivity : AppCompatActivity() {

    private lateinit var userDatabase: UserDatabase
    private lateinit var loginButton: Button
    private lateinit var usernameEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var registerLink: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        // 初始化视图组件
        loginButton = findViewById(R.id.login_button)
        usernameEditText = findViewById(R.id.username_edit_text)
        passwordEditText = findViewById(R.id.password_edit_text)
        registerLink = findViewById(R.id.register_link)


        userDatabase = UserDatabase.getDatabase(applicationContext)

        // 设置登录按钮的点击事件
        loginButton.setOnClickListener {
            val username = usernameEditText.text.toString()
            val password = passwordEditText.text.toString()

            if (username.isNotEmpty() && password.isNotEmpty()) {
                // 异步执行登录操作
                loginButton.isEnabled = false


                CoroutineScope(Dispatchers.IO).launch {
                    val user = userDatabase.userDao().getUserByUsername(username)

                    withContext(Dispatchers.Main) {
                        loginButton.isEnabled = true


                        if (user != null && PasswordUtils.checkPassword(password, user.password)) {
                            // 登录成功，保存用户数据到 SharedPreferences
                            saveUserDataToSharedPreferences(user)

                            // 显示登录成功的 Toast
                            Toast.makeText(this@LoginActivity, "登录成功", Toast.LENGTH_SHORT).show()

                            // 跳转到主页面
                            val intent = Intent(this@LoginActivity, MainActivity::class.java)
                            startActivity(intent)
                            finish()  // 结束登录界面，避免返回时再次显示
                        } else {
                            Toast.makeText(this@LoginActivity, "用户名或密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            } else {
                Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show()
            }
        }

        // 设置注册链接的点击事件，跳转到 RegisterActivity
        registerLink.setOnClickListener {
            val intent = Intent(this@LoginActivity, RegisterActivity::class.java)
            startActivity(intent)  // 跳转到注册页面
        }
    }

    private fun saveUserDataToSharedPreferences(user: User) {
        // 获取 SharedPreferences 实例
        val sharedPreferences = getSharedPreferences("UserPrefs", Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()

        // 存储用户名、昵称和密码
        editor.putString("username", user.username)
        editor.putString("nickname", user.nickname)
        editor.putString("password", user.password)  // 注意：这里保存的是加密后的密码
        editor.apply()  // 提交保存
    }
}
